﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using AiFrame.InterfaceLib.MVP;
using AiFrameDemo.CustomerData.Core.DataStore;
using AiFrameDemo.CustomerData.Core.Views;
using AiFrameDemo.Lib.Model;

namespace AiFrameDemo.CustomerData.Core.ViewModel
{
    public class CustomerDataViewModel: ViewModelBase, IDataErrorInfo, IDataSourceProvider<Customer>
    {
        private ICustomerDataView _view;
        private Customer _customer;
        private IList _list;

        public CustomerDataViewModel(ICustomerDataView view)
        {
            _view = view;
            _customer = new Customer();
            _list = LoadCustomerList();            
            _view.BindToViewModel(this);
            
        }

        #region Datafields

        public string CustomerNumber
        {
            get { return _customer.CustomerNumber; }
            set
            {
                if (_customer.CustomerNumber == value)
                    return;

                _customer.CustomerNumber = value;
                OnPropertyChanged("CustomerNumber");
            }
        }
        
        public string Firstname
        {
            get { return _customer.Firstname; }
            set
            {
                if (_customer.Firstname == value)
                    return;

                _customer.Firstname = value;
                OnPropertyChanged("Firtname");
            }
        }

        public string Lastname
        {
            get { return _customer.Lastname; }
            set
            {
                if (_customer.Lastname == value)
                    return;

                _customer.Lastname = value;
                OnPropertyChanged("Lastname");
            }
        }

        public DateTime Birthday
        {
            get { return _customer.Birthday; }
            set
            {
                if (_customer.Birthday == value)
                    return;

                _customer.Birthday = value;
                OnPropertyChanged("Birthday");
            }
        }

        public string CurrentCustomerDisplay
        {
            get
            {
                if (_customer.IsValid)
                    return string.Format("Current customer: {1} {0} (Customer number: {2})", Lastname, Firstname,
                                     CustomerNumber);
                else
                    return "Current customer: Please enter contact details.";
            }
        }

        public Customer Customer
        {
            get { return _customer; }
            set
            {
                if (value == null)
                    return;

                _customer = DaoFactory.Instance.CustomerStore.FindByID(value.ID);
                CustomerDataRegistry.Instance.CoreInterface.PluginManager.InvokeNewDatasetAssignedEvent<Customer>(
                    _view.SubWindowContainer);
                OnPropertyChanged("Customer");
            }
        }

        public IList CustomerListValues
        {
            get
            {
                if (_list.Count == 0)
                    _list.Add(new KeyValuePair<Customer, string>(null, "<No dataset available>"));

                return _list;
            }
            set
            {
                _list = value;
                OnPropertyChanged("CustomerListValues");
                _view.ResetCustomersDataSource();
            }
        }
        
        #endregion

        private IList LoadCustomerList()
        {
            var customerList = DaoFactory.Instance.CustomerStore.FindAll().ToList();
            var list = new ArrayList(customerList.Count);

            foreach (var customer in customerList)
            {
                list.Add(new KeyValuePair<Customer, string>(customer,
                                                            string.Format("{0}: {1} {2}", customer.CustomerNumber,
                                                                          customer.Firstname, customer.Lastname)));
            }
            return list;
        }

        #region Validation

        public bool IsValid
        {
            get
            { return _customer.IsValid; }
        }
        
        public string this[string propertyName]
        {
            get { return _customer[propertyName]; }
        }

        public string Error
        {
            get { return _customer.Error; }
        }
        
        #endregion

        public void UserWantsToAddCustomer()
        {
            CustomerDataRegistry.Instance.CoreInterface.WindowManager.CloseWindow(_view);

            var dataView = CustomerFactories.CustomerDataViewFactory.CreateCustomerView();
            var viewModel = new CustomerDataViewModel(dataView);

            CustomerDataRegistry.Instance.CoreInterface.WindowManager.RegisterWindow(dataView);
        }

        public void UserWantsToSaveCustomer()
        {
            if (!_customer.IsValid)
            {
                _view.DisplayError("The customer could not be saved because one or more fields are not filled in correctly.");
                return;
            }

            try
            {
                DaoFactory.Instance.CustomerStore.SaveOrUpdate(_customer);
                _view.InformUser("Your data hase been successfully saved.");
                CustomerListValues =  LoadCustomerList();
            }
            catch (Exception e)
            {
                _view.DisplayError("Error: " + e.Message);
            }
        }

        public void SetDataSource(Customer dataSource)
        {
            _customer = dataSource;
        }

        public Customer GetDataSource()
        {
            return _customer;
        }
    }
}
